#!/usr/bin/env bash
set -euo pipefail

stop_by_pidfile() {
  local pidfile="$1"
  if [ -f "$pidfile" ]; then
    local pid
    pid=$(cat "$pidfile" || true)
    if [ -n "${pid}" ] && kill -0 "$pid" 2>/dev/null; then
      echo "Stopping PID $pid from $pidfile"
      kill "$pid" || true
      sleep 2
      if kill -0 "$pid" 2>/dev/null; then
        echo "Force killing PID $pid"
        kill -9 "$pid" || true
      fi
    else
      echo "PID in $pidfile is not running."
    fi
    rm -f "$pidfile"
  fi
}

cd "$(dirname "$0")"

stop_by_pidfile runbot.pid
stop_by_pidfile position_close.pid

# Fallback: Stop python runbot processes if still running
pids=$(ps aux | grep -E "python\s+runbot.py" | grep -v grep | awk '{print $2}')
if [ -n "${pids}" ]; then
  echo "Stopping remaining runbot.py PIDs: ${pids}"
  kill ${pids} || true
  sleep 2
  pids_left=$(ps aux | grep -E "python\s+runbot.py" | grep -v grep | awk '{print $2}')
  if [ -n "${pids_left}" ]; then
    echo "Force killing remaining PIDs: ${pids_left}"
    kill -9 ${pids_left} || true
  fi
fi

echo "Done."
